<template>
  <div class="updatePhoto">
    <img :src="img" alt="" class="img" ref="img" />
    <div class="toolbar">
      <div class="cancel" @click="$emit('close')">取消</div>
      <div class="confirm" @click="onConfirm">完成</div>
    </div>
  </div>
</template>

<script>
import "cropperjs/dist/cropper.css";
import Cropper from "cropperjs";
import { updateUserPhoto } from "@/api/login.js";
export default {
  props: {
    img: {
      type: [String, Object],
      require: true,
    },
  },
  data() {
    return {
      cropper: null,
    };
  },
  mounted() {
    const image = this.$refs.img;
    this.cropper = new Cropper(image, {
      // 配置裁剪参数
      viewMode: 1,
      dragMode: "move",
      aspectRatio: 1,
      autoCropArea: 1,
      cropBoxMovable: false,
      cropBoxResizable: false,
      background: false,
    });
  },
  methods: {
    onConfirm() {
      // 基于服务端的裁切使用getData方法获取裁切参数
      // console.log(this.cropper.getData())
      // 纯客户端的裁切使用getCroppedCanvas获取裁切文件对象
      this.cropper.getCroppedCanvas().toBlob((blob) => {
        this.updatePhoto(blob);
        console.log(blob, "这是blob");
      });
    },
    async updatePhoto(blob) {
      // 接口要求必须传formData格式
      const formData = new FormData();
      formData.append("photo", blob);
      console.log(formData, "这是formData");
      try {
        const { data } = await updateUserPhoto(formData);
        console.log(data,'这是后台返回的图片地址')
        this.$emit("close"); //关闭弹窗
        this.$emit("updatePhoto", data.data.photo); //更新图片
        this.$toast.success("更新成功");
      } catch (err) {
        this.$toast.fail("更新失败");
      }
    },
  },
};
</script>

<style scoped lang="less">
.updatePhoto {
  height: 100%;
  // display: flex;
  // justify-content: center;
  // align-items: center;
  background-color: #000;
  .img {
    max-width: 100%;
    display: block;
  }
  .toolbar {
    // border: 1px solid blue;
    position: fixed;
    bottom: 0px;
    left: 0px;
    right: 0px;
    display: flex;
    justify-content: space-between;
    .cancel,
    .confirm {
      width: 90px;
      height: 90px;
      font-size: 40px;
      display: flex;
      justify-content: center;
      align-items: center;
      color: #fff;
    }
  }
}
</style>